package com.is.add.service.impl;

import com.github.pagehelper.PageHelper;
import com.is.add.controller.vo.JsonResultVO;
import com.is.add.controller.vo.SettlementVO;
import com.is.add.enmus.OrderStatus;
import com.is.add.event.ApiLogPublisher;
import com.is.add.mapper.*;
import com.is.add.model.*;
import com.is.add.service.GoodsService;
import com.is.add.service.OldGoodsService;
import com.is.add.service.OrderService;
import com.is.add.service.SettleService;
import com.is.add.util.DateUtil.DateStyle;
import com.is.add.util.DateUtil.DateUtil;
import com.is.add.util.DimensionUtil.DataCount;
import com.is.add.util.ExcelUtil.ExcelUtil;
import com.is.add.util.ExcelUtil.GetPath;
import com.is.add.util.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class SettleServiceImpl implements SettleService {
    private static String excelPath = "/home/settlePT/excel/";
    private static final String FILE_SEPARATOR = System.getProperties().getProperty("file.separator");
    private String SETTLE_START_TIME = DateUtil.DateToString(new Date(),DateStyle.YYYY_MM_DD_HH_MM_SS);
    private Boolean REFRESH_USER_ORDER_FIX = false;         //userorder_fixed表是否需要更新的标志。
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private PreDepositMapper preDepositMapper;
    @Autowired
    private PreDepositItemMapper preDepositItemMapper;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private SettlementMapper settlementMapper;
    @Autowired
    private SettleDocumentMapper settleDocumentMapper;
    @Autowired
    private OldGoodsService oldGoodsService;
    @Autowired
    private GoodsService goodsService;

    /**
     * 预结算查询
     */
    @Override
    public List<SettlementVO> loadSettleData(Map<String,String> map) throws Exception {
        String[] dimensionList ={"shop","payType"};
//        DataCount data = orderService.getAllOrder(dimensionList,map);
        DataCount data = orderService.getRecentlyOrder(dimensionList,map);
        List<SettlementVO> list = new ArrayList<>();
        List<DataCount> shopList = data.getSubSettlements();
         if(!shopList.isEmpty()){
            for (DataCount d :shopList){
                SettlementVO vo = new SettlementVO(0,0.0);
                int shopId = Integer.valueOf(d.getValue());
                vo.setShopId(shopId);
                Object shop = this.shopMapper.selectByPrimaryKey(shopId);
                Map<String, Object> shopMap = objectToMap(shop);
                vo.setShopCode(shopMap.get("shopCode").toString());
                vo.setShopName(d.getTitle());
                vo.setOrderNum(d.getCount());
                vo.setSettleNum(d.getOrderNum());
                vo.setTotalSum(d.getTotalSum());
                vo.setTotalFee(d.getFeeSum());
                vo.setPaySum(d.getPaySum());
                vo.setTotalSubsidySum(d.getSubsidySum());
                vo.setSettleSum(d.getTotalSum()*0.9);
                vo.setRealSettleSum(d.getSettlementSum());
                //goods历史
                List<OldGoods> oldGoodsList = this.oldGoodsService.findOldGoodsByShopAndDate(shopId,map.get("startTime"),map.get("endTime"));
                for (OldGoods g:oldGoodsList){
                    vo.setGoodsTotalNum(vo.getGoodsTotalNum()+g.getTotalNum());
                }
                //已上线7天内goods
                List<Goods> goodsList = this.goodsService.findGoodsByShopAndDate(shopId,map.get("startTime"),map.get("endTime"));
                for (Goods g:goodsList){
                    vo.setGoodsTotalNum(vo.getGoodsTotalNum()+g.getTotalNum());
                }
                for (DataCount payType :  d.getSubSettlements()){
                    String type = payType.getValue();
                    switch (type) {
                        case "VIP":
                            vo.setMemberPaySum(payType.getPaySum());
                            vo.setMemberSettleSum(payType.getSettlementSum());
                            vo.setMemberSubsidySum(payType.getSubsidySum());
                            break;
                        case "ALIPAY":
                            vo.setAliPaySum(payType.getPaySum());
                            vo.setAliPaySettleSum(payType.getSettlementSum());
                            vo.setAliPaySubsidySum(payType.getSubsidySum());
                            break;
                        case "FREE":
                            vo.setFreeSettleSum(payType.getSettlementSum());
                            vo.setFreeSubsidySum(payType.getSubsidySum());
                            break;
                        default:
                            vo.setWxPaySum(payType.getPaySum());
                            vo.setWxSettleSum(payType.getSettlementSum());
                            vo.setWxSubsidySum(payType.getSubsidySum());
                            break;
                    }
                }
                list.add(vo);
            }
         }
        ApiLogPublisher.publishEvent("查询未结算数据", null);
        return list;
    }

    /**
     * 修改结算状态
     * @param settlementIds     结算单IDs
     * @param newStatus         新结算状态
     * @return                  JsonResultVO
     */
    @Transactional
    @Override
    public JsonResultVO updateSettlementStatus(String settlementIds, Integer newStatus) {
        try {
            /** 修改订单 结算状态  */
            List<Integer> idList = new ArrayList<>();
            for (String s : settlementIds.split(",")) {
                Orders orderEx = new Orders();
                orderEx.setSettleStatus(newStatus);
                Example ordersExample = new Example(Orders.class);
                int settlementId = Integer.valueOf(s);
                SettleDocument settle = this.settleDocumentMapper.selectByPrimaryKey(settlementId);
                ordersExample.createCriteria().andEqualTo("settleNo", settle.getSettleNo()).andEqualTo("shopId", settle.getShopId());
                this.orderMapper.updateByExampleSelective(orderEx, ordersExample);
                idList.add(settlementId);
            }
            /** 修改结算单 结算状态  */
            Example example = new Example(SettleDocument.class);
            example.createCriteria().andIn("settlementId", idList);
            SettleDocument settle = new SettleDocument();
            settle.setSettleStatus(newStatus);
            settle.setOptTime(new Date());
            this.settleDocumentMapper.updateByExampleSelective(settle, example);
            /** 合并到生产结算单表  */
            if (newStatus == 4){          //审核后发布(场馆可查)
                /** 更新 userorder_fixed 表（重新写入修复后的订单数据） */
                if (REFRESH_USER_ORDER_FIX){
                    this.orderMapper.refreshUserOrderFix(SETTLE_START_TIME);
                    REFRESH_USER_ORDER_FIX = false;             //设为已更新状态
                }
                for (String s : settlementIds.split(",")) {
                    this.settlementMapper.mergeSettlement(Integer.valueOf(s));
                }
            }
            if (newStatus == 5){
                Example ex = new Example(Settlement.class);
                ex.createCriteria().andIn("settlementId", idList);
                Settlement settlement = new Settlement();
                settlement.setSettleStatus(newStatus);
                settlement.setOptTime(new Date());
                this.settlementMapper.updateByExampleSelective(settlement, ex);
            }
            String settleStatusName = "未结算";
            if(newStatus == 2){
                settleStatusName = "已生成，待确认";
            }else if(newStatus == 3){
                settleStatusName = "已确认，待审核";
            }else if(newStatus == 4){
                settleStatusName = "已审核，待付款";
            }else if(newStatus == 5){
                settleStatusName = "已付款";
            }
            ApiLogPublisher.publishEvent("修改结算状态，状态："+ settleStatusName, null);
            return new JsonResultVO(JsonResultVO.SUCCESS,"更新成功");
        }catch (Exception e){
            return new JsonResultVO(JsonResultVO.FAILURE,"发生异常");
        }
    }

    /**
     * 修复结算单
     * @param shopIds           场馆IDs
     * @param startTime         开始时间
     * @param endTime           结束时间
     * @return                  JsonResultVO
     */
    @Override
    public JsonResultVO fixAndCheckSettleOrders(String shopIds, String startTime, String endTime) {
        /** 修复订单  */
        Map<String, Object> map = new HashMap<>();
        map.put("startTime",startTime + " 00:00:00");
        map.put("endTime",endTime + " 23:59:59");
        String [] fixItems = {"fixFee","fixSettle","fixSubsidy"};
        map.put("fixItems",fixItems);
        String[] shopId =shopIds.trim().split(",");
        if (!shopId[0].equals("-1")){//  -1表示所有场馆
            map.put("shopIds",shopId);
        }
        int result = this.orderService.updateSettleFix(map);
        if (result >= 0){   //成功修复
            /** 生成结算单  */
            Map<String, Object> checkMap = new HashMap<>();
            startTime = startTime + " 00:00:00";
            endTime = endTime + " 23:59:59";
            checkMap.put("startTime",startTime);
            checkMap.put("endTime",endTime);
            checkMap.put("settleStatus","1");
            checkMap.put("orderStatus",OrderStatus.VerifiedDateOut.name());
            if (!shopId[0].equals("-1")) {//  -1表示所有场馆
                checkMap.put("shop",shopId);
            }
            List<Orders> check = this.orderMapper.findSettleOrders(checkMap);
                List<Integer> shopList = new ArrayList<>();
                for (Orders order: check){
                    Integer shop = order.getShopId();
                    if (!shopList.contains(shop)) {//  去除重复 场馆ID
                        try {
                            Boolean insertResult = calculateSettleDocumentData(shop, startTime, endTime);

                            if (insertResult) {
                                shopList.add(shop);
                            } else {
                                return new JsonResultVO(JsonResultVO.FAILURE, "添加结算单失败");
                            }
                        }catch (Exception e){
                            System.out.println(e.toString());
                            System.out.println("场馆ID" + shop + "--订单ID" + order.getOrderId());
                        }
                    }
                }
            SETTLE_START_TIME = startTime;
            REFRESH_USER_ORDER_FIX = true;         //设为需要更新状态
            ApiLogPublisher.publishEvent("修复并生成结算单", null);
            return new JsonResultVO(JsonResultVO.SUCCESS,"已生成");
        }else {
            return new JsonResultVO(JsonResultVO.FAILURE,"修复失败");}
    }

    /**
     * 新结算单查询
     * @param map       关键字，起止时间，结算状态
     * @return          SettlementVO
     */
    @Override
    public List<SettlementVO> findSettleDocument(Map<String, Object> map) {
        List<SettleDocument> settlementList = this.settleDocumentMapper.findSettleDocument(map);
        return SettlementVO.generateBy(settlementList);
    }

    /**
     * 备用金转存
     * @param settlementIds         结算单IDs
     * @return                      JsonResultVO
     */
    @Override
    public JsonResultVO insertPreDepositSettleData(String settlementIds) {
        for (String s : settlementIds.split(",")) {
            try {
                SettleDocument settle = this.settleDocumentMapper.selectByPrimaryKey(Integer.valueOf(s));
                if (settle != null && settle.getPreDepositStatus() == 0) {
                    if (settle.getMemberSettleSum() > 0){
                        Double addSum = settle.getMemberSettleSum(); //转存金额
                        Example shopEx = new Example(PreDeposit.class);
                        shopEx.createCriteria().andEqualTo("shopId", settle.getShopId());
                        int count = this.preDepositMapper.selectCountByExample(shopEx);
                        if (count <= 0) {
                            PreDeposit newDeposit = new PreDeposit();
                            newDeposit.setShopId(settle.getShopId());
                            newDeposit.setType(2);
                            newDeposit.setVersion(0);
                            newDeposit.setName("预存金");
                            newDeposit.setCreateTime(new Date());
                            newDeposit.setBalance(0.0);
                            newDeposit.setRechargeSum(0.0);
                            newDeposit.setDeductSum(0.0);
                            newDeposit.setStatus(1);
                            newDeposit.setRemark("创建");
                            this.preDepositMapper.insert(newDeposit);
                        }
                        //更新备用金金额
                        List<PreDeposit> preDepositList = this.preDepositMapper.selectByExample(shopEx);
                        if (preDepositList.size() > 0) {
                            PreDeposit preDeposit = preDepositList.get(preDepositList.size() - 1);
                            Double oldSum = preDeposit.getBalance();    //原始金额
                            preDeposit.setStatus(1);
                            preDeposit.setBalance(oldSum + addSum);
                            preDeposit.setRechargeSum(preDeposit.getRechargeSum() + addSum);
                            this.preDepositMapper.updateByPrimaryKey(preDeposit);

                            //插入一条备用金明细记录
                            PreDepositItem item = new PreDepositItem();
                            item.setPreDepositId(preDeposit.getId());
                            item.setVersion(0);
                            item.setOldSum(oldSum);
                            item.setChangeSum(addSum);
                            item.setNewSum(oldSum + addSum);
                            item.setOrderNumber(settle.getSettleNo());
                            item.setChangeType("结算转存");
                            item.setOptTime(new Date());
                            item.setRemark("周结算转存");
                            this.preDepositItemMapper.insert(item);
                        }
                    }
                    settle.setPreDepositStatus(1);
                    this.settleDocumentMapper.updateByPrimaryKeySelective(settle);
                }
            }catch (Exception x){
                x.getMessage();
                return new JsonResultVO(JsonResultVO.FAILURE,"发生异常");
            }
        }
        ApiLogPublisher.publishEvent("备用金转存", null);
        return new JsonResultVO(JsonResultVO.SUCCESS,"转存完毕");
    }

    /**
     * 结算单下的订单
     */
    @Override
    public List<Orders> findOneSettleOrders(String settlementId, int pageNum, int pageSize) {
        SettleDocument settleDocument = this.settleDocumentMapper.selectByPrimaryKey(settlementId);
        Example example = new Example(Orders.class);
        example.createCriteria().andEqualTo("shopId",settleDocument.getShopId()).andEqualTo("settleNo",settleDocument.getSettleNo());
        PageHelper.startPage(pageNum, pageSize);
        return this.orderMapper.selectByExample(example);
    }

    /**
     * 导出周结算数据
     */
    @Override
    public void exportSettleDoc(HttpServletResponse response, String startTime, String endTime) {
        Map<String,Object> map = new HashMap<>();
        map.put("startTime",startTime + " 00:00:00");
        map.put("endTime",endTime + " 23:59:59");
        List<SettleDocument> settlementList = this.settleDocumentMapper.findSettleDocument(map);
        //设置路径
        String docsPath = GetPath.getDirectoryPath("src","main","resources","templates");       //模板文件路径
        String fileName = endTime+"周结算表"+".xls";           //导出Excel文件名
        String filePath = docsPath + FILE_SEPARATOR + fileName;

        filePath = excelPath + fileName;
        System.out.println("------filePath:"+filePath);
        //数据填充
        ExcelUtil<SettlementVO> ex = new ExcelUtil<SettlementVO>();
        String[] headers ={"结算单ID","结算时间","结算单编号","场馆Id","场馆编号","场馆名称","场次数","总金额","支付金额","补贴金额","手续费","会员支付金额","支付宝支付金额","微信支付金额","会员补贴金额","支付宝支付补贴金额","免费补贴金额","微信支付补贴金额","应结金额","实结金额","会员实结金额","支付宝实结金额","免费实结金额","微信实结金额","待结金额","结算状态","备注"};
        String[] columns={ "settlementId", "settleTime", "settleNo", "shopId", "shopCode", "shopName","settleNum","totalSum","paySum","totalSubsidySum","totalFee","memberPaySum","aliPaySum","wxPaySum","memberSubsidySum","aliPaySubsidySum","freeSubsidySum","wxSubsidySum","settleSum","realSettleSum","memberSettleSum","aliPaySettleSum","freeSettleSum","wxSettleSum","toBeSettleSum","settleStatus","remark"};
        try {
            OutputStream out = new FileOutputStream(filePath);
            ex.exportExcel(endTime+"周结算表",headers, columns, SettlementVO.generateBy(settlementList), out, DateStyle.YYYY_MM_DD_HH_MM_EN.getValue());
            ApiLogPublisher.publishEvent("导出周结算表："+fileName, null);
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.err.println("文件未找到");
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("IO异常错误");
        } catch (Exception e) {
            e.printStackTrace();
        }
        ExcelUtil.download(filePath, response);
    }

    /**
     * 计算结算数据,生成结算单
     * @param shop          场馆ID
     * @param startTime     开始时间
     * @param endTime       截止时间
     * @return              boolean
     */
    private Boolean calculateSettleDocumentData(Integer shop, String startTime, String endTime) {
        /** 计算各项值  */
        //保证金类型
        Example example = new Example(PreDeposit.class);
        example.createCriteria().andEqualTo("shopId", shop);
        List<PreDeposit> preDeposit = this.preDepositMapper.selectByExample(example);
        int preType = 1;
        if (preDeposit.size()>0){
            preType = preDeposit.get(preDeposit.size()-1).getType();
        }
        Map<String, Object> findMap = new HashMap<>();
        findMap.put("startTime",startTime);
        findMap.put("endTime",endTime);
        String[] shopId = {shop.toString()};
        findMap.put("shop",shopId);
        List<Orders> ordersList = this.orderMapper.findSettleOrders(findMap);
        System.out.println(shop+"本期结算订单总条数：" + ordersList.size());
        Integer orderNum = 0;   //计算订单数量

        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        String settleNo =c.get(Calendar.YEAR)+String.format("%02d",c.get(Calendar.MONTH)+1)+String.format("%02d",c.get(Calendar.DAY_OF_MONTH))+"-"+RandomUtils.generateString(15);

        SettleDocument settlement = new SettleDocument(0,0.0);
        settlement.setSettleNo(settleNo);
        settlement.setVersion(0);
        Date endDate = new Date();
        Date start = new Date();
        Date end = new Date();
        DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {//加一秒
            start = fmt.parse(startTime);
            end = fmt.parse(endTime);
            endDate.setTime(end.getTime() + 1000);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        settlement.setStartSettleTime(start);
        settlement.setEndSettleTime(end);
        settlement.setSettleTime(endDate);
        settlement.setShopId(shop);

        // 统计加和
        for (Orders o : ordersList){
            try {
                // n_type = 2，5 ,计算已使用订单 和 过期未验证订单 S1、S3
                if (o.getSettleStatus()==1 && (o.getOrderStatus() ==3 || o.getOrderStatus() ==4)){
                    if (o.getPaySum()>0 && o.getPayType().equals("会员卡")){
                        settlement.setMemberPaySum(settlement.getMemberPaySum() + o.getPaySum());
                    }else if (o.getPaySum() >0 && o.getPayType().equals("支付宝")){
                        settlement.setAliPaySum(settlement.getAliPaySum() + o.getPaySum());
                    }else if (o.getPaySum() >0 && o.getPayType().equals("微信")){
                        settlement.setWxPaySum(settlement.getWxPaySum() + o.getPaySum());
                    }
                    settlement.setPaySum(settlement.getPaySum() + o.getPaySum());
                    settlement.setSettleNum(settlement.getSettleNum() + o.getOrderNum());
                    orderNum ++;
                }
                //n_type = 3 ,计算补贴  S2
                //未结算、已使用
                if (o.getSubsidyStatus() == 1 && o.getOrderStatus() == 3 && o.getUsed() == 1) {
                    if (o.getSubsidySum() > 0 && (o.getPayType() == null)) {
                        settlement.setFreeSubsidySum(settlement.getFreeSubsidySum() + o.getSubsidySum());
                    } else if (o.getSubsidySum() > 0 && o.getPayType().equals("会员卡")) {
                        settlement.setMemberSubsidySum(settlement.getMemberSubsidySum() + o.getSubsidySum());
                    } else if (o.getSubsidySum() > 0 && o.getPayType().equals("支付宝")) {
                        settlement.setAliPaySubsidySum(settlement.getAliPaySubsidySum() + o.getSubsidySum());
                    } else if (o.getSubsidySum() > 0 && o.getPayType().equals("微信")) {
                        settlement.setWxSubsidySum(settlement.getWxSubsidySum() + o.getSubsidySum());
                    }
                    settlement.setTotalSubsidySum(settlement.getTotalSubsidySum() + o.getSubsidySum());
                }
            }catch(Exception e){
                System.out.println(e.toString() + " - 出现异常的订单ID=" + o.getOrderId());
            }
        }
        settlement.setOrderNum(orderNum);
        List<OldGoods> oldGoodsList = this.oldGoodsService.findOldGoodsByShopAndDate(shop,startTime,endTime);
        for (OldGoods g:oldGoodsList){
            settlement.setGoodsTotalNum(settlement.getGoodsTotalNum()+g.getTotalNum());
        }
        //已上线7天内goods
        List<Goods> goodsList = this.goodsService.findGoodsByShopAndDate(shop,startTime,endTime);
        for (Goods g:goodsList){
            settlement.setGoodsTotalNum(settlement.getGoodsTotalNum()+g.getTotalNum());
        }
        //结算
//        settlement.setSettleSum((settlement.getPaySum() + settlement.getTotalSubsidySum()) * 0.9);
//        settlement.setRealSettleSum((settlement.getPaySum() * 0.9 - settlement.getTotalSubsidySum() * 0.1));
//        settlement.setMemberSettleSum((settlement.getMemberPaySum() * 0.9 - settlement.getMemberSubsidySum() * 0.1));
//        settlement.setAliPaySettleSum((settlement.getAliPaySum() * 0.9 - settlement.getAliPaySubsidySum() * 0.1));
//        settlement.setWxSettleSum((settlement.getWxPaySum() * 0.9 - settlement.getWxSubsidySum() * 0.1));
//        settlement.setFreeSettleSum(0 - settlement.getFreeSubsidySum()*0.1);
//        //总
//        settlement.setTotalSum(settlement.getPaySum() + settlement.getTotalSubsidySum());
//        settlement.setTotalFee((settlement.getPaySum() + settlement.getTotalSubsidySum()) * 0.1);
//        settlement.setOptTime(new Date());
//        settlement.setOptUser(52);
//        settlement.setSettlePro(1.0);
//        settlement.setSettleType(2);
//        settlement.setSettleStatus(2);
//        settlement.setPreDepositType(preType);
//        settlement.setPreDepositStatus(0);
//        settlement.setFixSettleSum(0.0);
        ////修改免费预订的补贴不计算服务费 modify by liuyan 2017-11-9
        settlement.setSettleSum((settlement.getPaySum() + settlement.getTotalSubsidySum()) * 0.9 + settlement.getFreeSubsidySum()*0.1);
        settlement.setRealSettleSum((settlement.getPaySum() * 0.9 - (settlement.getTotalSubsidySum() - settlement.getFreeSubsidySum()) * 0.1));
        settlement.setMemberSettleSum((settlement.getMemberPaySum() * 0.9 - settlement.getMemberSubsidySum() * 0.1));
        settlement.setAliPaySettleSum((settlement.getAliPaySum() * 0.9 - settlement.getAliPaySubsidySum() * 0.1));
        settlement.setWxSettleSum((settlement.getWxPaySum() * 0.9 - settlement.getWxSubsidySum() * 0.1));
        settlement.setFreeSettleSum(0.0);
        //总
        settlement.setTotalSum(settlement.getPaySum() + settlement.getTotalSubsidySum());
        settlement.setTotalFee((settlement.getPaySum() + settlement.getTotalSubsidySum() - settlement.getFreeSubsidySum()) * 0.1);
        settlement.setOptTime(new Date());
        settlement.setOptUser(52);
        settlement.setSettlePro(1.0);
        settlement.setSettleType(2);
        settlement.setSettleStatus(2);
        settlement.setPreDepositType(preType);
        settlement.setPreDepositStatus(0);
        settlement.setFixSettleSum(0.0);
        //修改所有补贴不收取服务费 modify by liuyan 2017-12-5
        //应结金额是：所有支付费用 + 所有补贴费用 - 支付费用的服务费
//        settlement.setSettleSum(settlement.getPaySum() * 0.9 + settlement.getTotalSubsidySum());
//        //实结金额是：所有支付费用 - 支付费用的服务费
//        settlement.setRealSettleSum(settlement.getPaySum() * 0.9);
//        //会员卡结算金额是：会员卡支付费用 - 会员卡支付费用的服务费
//        settlement.setMemberSettleSum(settlement.getMemberPaySum() * 0.9);
//        //支付宝结算金额是：支付宝支付费用 - 支付宝支付费用的服务费
//        settlement.setAliPaySettleSum(settlement.getAliPaySum() * 0.9);
//        //微信结算金额是：微信支付费用 - 微信支付费用的服务费
//        settlement.setWxSettleSum(settlement.getWxPaySum() * 0.9);
//        //免费结算金额为0
//        settlement.setFreeSettleSum(0.0);
//        //总
//        //总计金额是：所有支付费用 + 所有补贴费用
//        settlement.setTotalSum(settlement.getPaySum() + settlement.getTotalSubsidySum());
//        //总计服务费是：所有支付费用的服务费
//        settlement.setTotalFee(settlement.getPaySum() * 0.1);
//        settlement.setOptTime(new Date());
//        settlement.setOptUser(52);
//        settlement.setSettlePro(1.0);
//        settlement.setSettleType(2);
//        settlement.setSettleStatus(2);
//        settlement.setPreDepositType(preType);
//        settlement.setPreDepositStatus(0);
//        settlement.setFixSettleSum(0.0);
        //end modify


        int result = this.settleDocumentMapper.insert(settlement);

        if (result > 0) {
            /** 生成成功，修改订单  */
            Map<String, Object> updateMap = new HashMap<>();
            updateMap.put("startTime", startTime);
            updateMap.put("endTime", endTime);
            updateMap.put("shop", shop);
            updateMap.put("settleNo", settleNo);
            //修改已使用和过期订单 结算状态
            updateMap.put("settleStatus", 1);
            updateMap.put("orderStatus", OrderStatus.VerifiedDateOut.name());
            int count = 0;
            try{
                count = this.orderMapper.updateSettleOrders(updateMap);
            }catch (Exception e){
                System.out.println(e.toString() + "修改订单结算状态" + settleNo);
            }
            // 修改补贴订单
            updateMap.remove("settleStatus");
            updateMap.put("subsidyStatus", 1);
            updateMap.put("orderStatus", OrderStatus.Verified.name());
            try {
                if(count > 0) {
                    this.orderMapper.updateSettleOrders(updateMap);
                }
            }catch (Exception e){
                System.out.println(e.toString() + "修改补贴状态" + settleNo);
            }
            return true;
        }else{
            return false;
        }

    }

    public static Map<String, Object> objectToMap(Object obj) throws Exception {
        if(obj == null){
            return null;
        }

        Map<String, Object> map = new HashMap<String, Object>();

        Field[] declaredFields = obj.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            map.put(field.getName(), field.get(obj));
        }

        return map;
    }
}

